package topofstack.networkserverutils.net;

import java.io.BufferedReader;
import java.io.StringReader;

import topofstack.networkserverutils.bean.Location;
import topofstack.networkserverutils.util.ShellEmulator;

public class GeoLocation {
	
	public static final int LATITUDE_INDEX = 2;
	public static final int LONGITUDE_INDEX = 6;
	
	public static Location get(String url) {
		String command = "host -t LOC " + url;
		String result = ShellEmulator.query(command);
		
		return parse(result);
	}
	// statdns.net
	private static Location parse(String input) {
		if (input == null)
			return null;

		BufferedReader reader = new BufferedReader(new StringReader(input));

		try {
			String line = reader.readLine();
			if(line.contains("no LOC record"))
				return null;
			else {
				String[] contents = line.trim().split(" ");
				int latDegree = Integer.parseInt(contents[LATITUDE_INDEX]);
				int latMinute = Integer.parseInt(contents[LATITUDE_INDEX + 1]);
				double latSecond = Double.parseDouble(contents[LATITUDE_INDEX + 2]);
				String latDirection = contents[LATITUDE_INDEX + 3];
				
				int longDegree = Integer.parseInt(contents[LONGITUDE_INDEX]);
				int longMinute = Integer.parseInt(contents[LONGITUDE_INDEX + 1]);
				double longSecond = Double.parseDouble(contents[LONGITUDE_INDEX + 2]);
				String longDirection = contents[LONGITUDE_INDEX + 3];
				
				return new Location(latDegree, latMinute, latSecond, latDirection, longDegree, longMinute, longSecond, longDirection);
			}
			
		} catch (Exception exception) {
			exception.printStackTrace();
			return null;
		}

	}
} 
